var app=getApp()
var util = require('../../utils/util')
var imgListUrl = []
Page({
    data: {
        quesorder: 0,
        array: [],
        optioncontent: null,
        nextquesid: null,
        optionsForQuesid: [],
        questypeid: 0,
        questypearray: ['单选题', '多选题', '问答题'],
        current: "survey",
        surveyname: null,
        surveydescription: null,
        surveyperoration: null,
        surveyStartTime: '',
        surveyendtime: "",
        queses: [],
        thanksWord: "感谢您填写我们的问卷！！！！",
        imgList:[],
        userName: "",
        imgListUrl:[],
        survey_id:""
    },
    onLoad(){
    },
    onShow(){
       var time = util.formatDate(new Date())
       this.setData({
        surveyStartTime: time,
        surveyendtime: time
       })

       var userInfo = wx.getStorageSync('userInfo')

       console.log(userInfo)
       this.setData({
           userName: userInfo.userName
       }) 
       console.log(this.data.userName)
    },
    bindDateChange: function (e) {
        this.setData({
            surveyendtime: e.detail.value
        })
    },
    bindStartDateChange: function (e) {
        this.setData({
            surveyStartTime: e.detail.value
        })
    },
    // 点击下一步触发
    surveycomplete: function (e) {
        // console.log(e)
        if(e.detail.value.surveyname !="" || e.detail.value.surveydescription !=""){
            this.setData({
                current: "ques",
                surveyname: e.detail.value.surveyname,
                surveydescription: e.detail.value.surveydescription,
                surveyperoration: e.detail.value.surveyperoration,
            })

            this.addSurveyList()
        }else{
            wx.showToast({
              title: '不可以为空喔',
              icon: "error"
            })
        }
           
    },

    ChooseImage() {
        wx.chooseImage({
          count: 3, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册或拍照选择
          success: (res) => {
            if (this.data.imgList.length != 0) {
              this.setData({
                imgList: this.data.imgList.concat(res.tempFilePaths)
              })
            } else {
              this.setData({
                imgList: res.tempFilePaths
              })
            }
          }
        });
    },
    ViewImage(e) {
        wx.previewImage({
          urls: this.data.imgList,
          current: e.currentTarget.dataset.url
        });
    },

    tosurvey: function () {
        this.setData({
            current: "survey",
        })
    },
    toques: function () {
        this.setData({
            current: "ques",
        })
    },
    newques: function () {
        this.setData({
            current: "option",
        })
    },
    bindTypeChange: function (e) {
        this.setData({
            questypeid: parseInt(e.detail.value)
        })
    },
    addoption: function () {
        var arrayy = this.data.array.concat(this.data.array.length + 1)
        this.setData({
            array: arrayy
        })
    },
    quescomplete: function (e) {
        this.setData({
            quesorder: this.data.quesorder + 1,
        })
        for (var i = 0; i < this.data.array.length; i++) {
            var optionkey = "option" + i;
            var optionnextkey = "optionnext" + i;
            var nextquesidd = e.detail.value[optionnextkey]
            if (nextquesidd == '')
                nextquesidd = this.data.quesorder + 1;

            var optionsForQuesidd = this.data.optionsForQuesid.concat([{ optioncontent: e.detail.value[optionkey], nextquesid: nextquesidd }])
            this.setData({
                optionsForQuesid: optionsForQuesidd
            })
        }
        //填空题
        if(this.data.questypeid==2)
        {
                        var optionsForQuesidd = [{ optioncontent: "", nextquesid: this.data.quesorder + 1 }]
            this.setData({
                optionsForQuesid: optionsForQuesidd
            })
        }

        var quesess = this.data.queses.concat([{ quescontent: e.detail.value.quescontent, questype: {"typeid": 1+parseInt(this.data.questypeid) }, quesorder: this.data.quesorder, quesrequired: e.detail.value.quesrequired, optionsForQuesid: this.data.optionsForQuesid }])
        this.setData({
            queses: quesess,
            questypeid:0,
        })
        this.setData({
            current: "ques",
        })
        this.setData({
            array: [],
            optionsForQuesid: [],
        })
    },


    // 提交问卷
    completeall: function () {

        this.setData({
            user: app.globalData.userInfo,
        })

        wx.showToast({
            title: '提交中',
            icon: 'loading',
            duration: 10000,
            mask: true
        })

        wx.hideToast()
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            mask: true
        })
        console.log(this.data)
        console.log(this.data.queses)

        this.getUrl()
    },


    addSurveyList(){
        wx.cloud.callFunction({
            name:"addSurveyList",
            data:{
                surveydesc: this.data.surveydescription,
                surveystarttime: this.data.surveyStartTime,
                surveyendtime: this.data.surveyendtime,
                surveyname: this.data.surveyname,
            }
        }).then(res=>{
            // console.log(res.result._id)
            this.setData({
                survey_id: res.result._id
            })
        })       
    },

    addSurveyDetails(){
        // console.log(this.data.userName)
        wx.cloud.callFunction({
            name:"addSurveyDetails",
            data:{
                _id: this.data.survey_id,
                desc:this.data.surveydescription,
                imageUrl: this.data.imgListUrl[0],
                name: this.data.surveyname,
                thankscontent: this.data.thanksWord,
                userName: this.data.userName,
                queses: this.data.queses
            }
        }).then(res=>{
            // console.log(res)
            wx.switchTab({
              url: "/pages/questionnaire/index",
            })
        })
    },
    addquesSwiper(){
        wx.cloud.callFunction({
            name:"addquesSwiper",
            data:{
                _id: this.data.survey_id,
                imageUrl: this.data.imgListUrl[0],
            }
        }).then(res=>{
            // console.log(res)
        })
    },
    getUrl(){
        let promiseArr = [];
         //  1, 将图片插到 云存储
         this.data.imgList.forEach((item,idx) => {
          let p = new Promise((resolve, reject)=>{
            wx.cloud.uploadFile({
              cloudPath: "surveys/" + Date.now() + '.jpg',
              filePath: item
            }).then(
              res=> {
                // console.log(res.fileID)
                wx.cloud.getTempFileURL({
                  fileList: [{
                    fileID: res.fileID,
                    maxAge: 60 * 60, // one hour
                  }]
                }).then(res => {
                  // get temp file URL
                  // console.log(res.fileList[0].tempFileURL)
                  // imgListUrl = this.data.imgListUrl
                  imgListUrl.push(res.fileList[0].tempFileURL)
                  // console.log(res.fileList[0].tempFileURL)
                  this.setData({
                    imgListUrl
                  })
                  resolve()
                })
              }
            )
          })
          promiseArr.push(p)
        })
        
        Promise.all(promiseArr).then(res => {
          // console.log(imgListUrl)
          this.addSurveyDetails()
          this.addquesSwiper()
        })
      },
})